package com.hk.Mgr.web.controller.app;

import java.math.BigDecimal;
import java.net.URI;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import com.google.gson.Gson;
import com.hk.Mgr.web.message.app.FYJZHOrderResponse;
import com.hk.Mgr.web.message.order.OrderInfoReq;
import com.hk.app.utils.UniqueVersion;
import com.hk.commons.*;
import com.hk.commons.entity.EncourageHistory;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.order.OrderContract;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.message.RequestMsg;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.OrderStrResp;
import com.hk.service.IEncourageHistory;
import com.hk.service.message.CouponResult;
import com.hk.service.order.*;
import com.hk.service.sys.IAnswer;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.OrderCommReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.view.OrderView;
import com.hk.commons.utils.order.OrderCreateMsg;
import com.hk.commons.vo.OrderStrMsg;
import com.hk.service.order.impl.OrderHandleContent;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;
import com.hk.service.view.IOrderView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = BaseCtrl.CommonRootPath + "/orderRoute")
public class AppOrderStrategyCtrl {
	private Logger logger = LoggerFactory.getLogger(AppOrderStrategyCtrl.class);

	private static final String JH_ACTIVITY_BEGIN = "JH_ACTIVITY_BEGIN";
	private static final String JH_ACTIVITY_END = "JH_ACTIVITY_END";

	@Autowired
	private IOrderView orderViewService;

	@Autowired
	private OrderHandleContent orderContent;

	@Autowired
	private IPayment payService;

	@Autowired
	private IProductInfo prodService;

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private IOrderInfo orderService;

    @Autowired
    private IOrderMonitor orderMonitorRepo;

	@Value("${msgserver.baseUrl}")
	private String msgServerHost;

	@Autowired
	private IParameter parameterService;

	@Autowired
	private IAnswer answerService;


	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private IEncourageHistory encourageHistoryService;

	@Autowired
	private IOrderContract orderContractService;

	@Value("${qingniu.pdf}")
	private String QN_PDF;


	private static final String ThreeEndUser = "ThreeEndUser";
	private static final String WhatNumberEnd = "WhatNumberEnd";
	private static final String OneDayEncourageMoney = "OneDayEncourageMoney";
	private static final String ThreeComboEncourageMoney = "ThreeComboEncourageMoney";
	private static final String ThreeComboEncourageTime = "ThreeComboEncourageTime";

	private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy.MM");



	@RequestMapping(value = "/getAll", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<OrderStrMsg>> getAll(@RequestBody OrderCommReq req) {

		ResponseBase<List<OrderStrMsg>> resp = new ResponseBase<List<OrderStrMsg>>();

		List<OrderStrMsg> orderList = new ArrayList<OrderStrMsg>();

		//Long userId = CheckUserId.checkId(req.getUserId());

		Long userId = req.getUserId();

		//Integer  confirmStatus = req.getConfirmStatus();

		Integer  confirmStatus = 2;
		
		logger.info("common/orderRoute/getAll info: userId ={},  confirmStatus={}"
		, userId, confirmStatus);
		
		
		if (userId == null) {
			resp.setResult(null);
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg("参数错误");
		}	
			
			
		if(confirmStatus != null && confirmStatus != 0){
			orderList = (List<OrderStrMsg>) orderContent.getAll(userId, confirmStatus);
		}else{
			orderList = (List<OrderStrMsg>) orderContent.getAll(userId);
		}	
		
		resp.setResult(orderList);
		resp.setSize(orderList.size());
		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setMsg("成功");
		
		return resp;

	}
	
	/**
	 * 交易记录调用该方法获取所有订单信息， 2.1版本之后使用
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/getAllOrderList", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<OrderStrMsg>> getAllOrderList(@RequestBody OrderCommReq req) {

		ResponseBase<List<OrderStrMsg>> resp = new ResponseBase<List<OrderStrMsg>>();

		if(req == null ||  req.getUserId() == null){
			resp.setResult(null);
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg("参数错误");
		} else {
			logger.info("common/orderRoute/getAllOrderList info: userId ={}", req.getUserId());
			List<OrderStrMsg> orderList = orderContent.getAll(req.getUserId());

			resp.setResult(orderList);
			resp.setSize(orderList.size());
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("成功");
		}

		return resp;
	}

	@RequestMapping(value = "/getAllOrderList2", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<OrderStrResp>> getAllOrderListVersion2(@RequestBody OrderCommReq req) {
		ResponseBase<List<OrderStrResp>> resp = new ResponseBase<>();

		if (req.getPageSize() == null) {
			req.setPageSize(20);
		}

		Long orderCreatedOnReq = req.getOrderCreatedOn();

		if (req.getUserId() == null) {
			resp.setResult(null);
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg("参数错误");
			return resp;
		}

		//限制销户用户-2.7.6
		SysUser user = sysUserService.findById(req.getUserId());
		if(user == null || user.getCloseAccount() == 1){
			resp.setResult(null);
			resp.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
			resp.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
			return resp;
		}

		List<OrderStrResp> resultList = new ArrayList<>();

		Map<String, List<OrderStrMsg>> results = new HashMap<>();

		List<OrderStrMsg> orderList = orderContent.getAllVersion2(req.getUserId(), req.getPageSize(), orderCreatedOnReq);

		for (OrderStrMsg orderStrMsg: orderList) {
			Long orderCreatedOn = Long.valueOf(orderStrMsg.getOrderCreatedOn());

			Timestamp timestamp = Timestamp.from(Instant.ofEpochMilli(orderCreatedOn));
			LocalDateTime orderCreatedOnDateTime = timestamp.toLocalDateTime();

			String key = orderCreatedOnDateTime.format(dateTimeFormatter);

			if (results.containsKey(key)) {
				results.get(key).add(orderStrMsg);
			} else {
				List<OrderStrMsg> orders = new ArrayList<>();
				orders.add(orderStrMsg);

				results.put(key, orders);
			}
		}

		for (String key: results.keySet()) {
			OrderStrResp orderStrResp = new OrderStrResp();
			orderStrResp.setMonth(key);
			orderStrResp.setOrderStrMsgList(results.get(key));
			resultList.add(orderStrResp);
		}

		Collections.sort(resultList, (o1, o2) -> -(o1.getMonth().compareTo(o2.getMonth())));
		resp.setResult(resultList);

		return resp;
	}

	/**
	 * 获取固定收益的订单, 2.1版本之后使用
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/getFixIncomOrder", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<OrderStrMsg>> getFixIncomOrder(@RequestBody OrderCommReq req) {

		ResponseBase<List<OrderStrMsg>> resp = new ResponseBase<List<OrderStrMsg>>();

		if(req == null || req.getUserId()== null){
			resp.setResult(null);
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误");
			return resp;
		}

		Long userId =  req.getUserId();

		logger.info("common/orderRoute/getAllOrderList info: userId ={}", req.getUserId());

		Integer  confirmStatus = ConstantOrderStatus.CONFIRM_STATUS__TRUE;

		List<OrderStrMsg> orderList = new ArrayList<OrderStrMsg>();
		orderList = (List<OrderStrMsg>) orderContent.getAll(userId, confirmStatus);
		
		resp.setResult(orderList);
		resp.setSize(orderList.size());
		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setMsg("成功");
		return resp;
	}


	@RequestMapping(value = "/getContractMsg")
	@ResponseBody
	public ResponseBase<Boolean> getContractMsg(@RequestBody OrderInfoReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();


		if (req == null || req.getOrderId() == null) {
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误，订单ID不存在！");
			return resp;
		}

		logger.info("getContractMsg orderId={]", req.getOrderId());

		OrderInfo orderInfo = orderService.findById(req.getOrderId());
		if(orderInfo == null){
			resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
			resp.setMsg("参数错误，订单不存在！");
			return resp;
		}

		SysUser user = sysUserService.findById( orderInfo.getUserId());
		if(user == null){
			resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
			resp.setMsg("用户不存在！");
			return resp;
		}


		/**
		 * 利用极光推送，发送相关信息给用户
		 */



		resp.setResultCode(StatusCode.SUCCESS.key());
		resp.setMsg("获取合同信息成功");
		resp.setResult(true);
		return resp;
	}



	/**
	 * get order list by order status
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/getOrderList", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<Map<String, Object>>> getOrderList(
			@RequestBody OrderCommReq req) {
		ResponseBase<List<Map<String, Object>>> resp = new ResponseBase<List<Map<String, Object>>>();

		List<Map<String, Object>> commOrderList = new ArrayList<Map<String, Object>>();

		Long userId = req.getUserId();

		Integer confirmStatus = req.getConfirmStatus();

		Integer payStatus = req.getPayStatus();

		Integer curPage = req.getCurPage();

		Integer pageSize = req.getPageSize();

		logger.info(
				"getDJOrder getList userId = {},payStatus={}, confirmStatus ={} curPage ={}, pageSize ={}",
				userId, payStatus, confirmStatus, curPage, pageSize);

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);

		if (userId == null || confirmStatus == null || payStatus == null) {
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());

			return resp;
		}

		hqlFilter.addEQFilter("confirmStatus", confirmStatus);

		hqlFilter.addEQFilter("payStatus", payStatus);

		logger.info("hqlFilter  = " + hqlFilter.getWhereAndOrderHql());

		List<OrderView> orderViewList = orderViewService.findByFilter(
				hqlFilter, curPage, pageSize);

		Long size = orderViewService.countByFilter(hqlFilter);

		logger.info("size  = " + size);

		for (OrderView orderView : orderViewList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orderId", orderView.getOrderId());
			map.put("orderCreatedOn",
					DateUtil.longToLongDate(orderView.getOrderCreatedOn()));
			map.put("prodName", orderView.getProductName());
			map.put("successAmount", orderView.getSuccessAmount());
			commOrderList.add(map);
		}

		logger.info("orderViewList  size  = " + orderViewList.size());

		resp.setResultCode(ResultCode.SUCC.getCode());
		resp.setResult(commOrderList);
		resp.setSize(size);

		return resp;
	}

	/**
	 * 创建订单接口,用富有金账户进行支付
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/createFYJZHOrder", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseBase<Long> createFYJZHOrder(@RequestBody OrderCommReq req, HttpServletRequest request) {

		ResponseBase<Long> resp = new ResponseBase<>();

		Long userId = req.getUserId();

		// 产品id
		Long productId = req.getProductId();

		// 购买金额
		BigDecimal amount = req.getBuyAmount();

		//加息券id
		Long userCardId  = req.getUserCardId();

		logger.info("common/orderRoute/createFYJZHOrder " +
						"info: userId = {}, productId={}, amount={}, userCardId={}",
						userId, productId,  amount, userCardId);

		if(userId == null || productId == null || amount == null){
			logger.info("参数错误，购买失败");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			resp.setMsg("参数错误，购买失败！");
			return resp;
		}


        String version = req.getV();
		logger.info("version 01 = {}", version);
        if (StringHelper.isEmpty(version)) {
            version = request.getParameter("v");
			logger.info("version 02 = {}", version);
        }

		logger.info("version 03 = {}", version);
		//检查订单信息，如果通过检查再创建订单，否则不创建订单
		CheckInfo checkInfo = prodService.checkBeforeCreateOrder(userId, productId, amount, userCardId, version);

		logger.info("checkBeforeCreateOrder result={}", checkInfo.toString());

		if(!checkInfo.getResult()){
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg(checkInfo.getResultMsg());
			logger.info("checkBeforeCreateOrder failed and will not create order ");
			return resp;
		}

		logger.info("checkBeforeCreateOrder success and will create order ");


		OrderInfo orderInfo = orderContent.createFYJZHOrder(null,
				userId, productId, userCardId, amount);

		if(orderInfo == null){
			logger.info("创建订单失败  ");
			resp.setResultCode(StatusCode.ERROR.key());
			resp.setMsg("订单创建失败");

		}else{
			logger.info("创建订单成功 orderId ={}", orderInfo.getId());

			resp.setResult(orderInfo.getId());
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("订单创建成功");

            //订单加入监控
            orderMonitorRepo.started(orderInfo);
		}

		return resp;

	}



	@RequestMapping(value = "/queryEncourage", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseBase<FYJZHOrderResponse> queryEncourage(@RequestBody OrderCommReq req) {
		ResponseBase<FYJZHOrderResponse> resp = new ResponseBase<>();

		if (req.getOrderId() == null) {
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			resp.setMsg("param error");
		} else {
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss");

			Parameter jhActivityBegin = parameterService.getByName(JH_ACTIVITY_BEGIN);
			Parameter jhActivityEnd = parameterService.getByName(JH_ACTIVITY_END);

			LocalDateTime now = LocalDateTime.now();

			LocalDateTime activityBegin = LocalDateTime.parse(jhActivityBegin.getValue01(), dateTimeFormatter);
			LocalDateTime activityEnd = LocalDateTime.parse(jhActivityEnd.getValue01(), dateTimeFormatter);

			FYJZHOrderResponse fyjzhOrderResponse = new FYJZHOrderResponse(req.getOrderId(), false, false, false, 0, false, false, false);

			if (now.compareTo(activityBegin) < 0) {
				resp.setResultCode(ResultCode.FAILED.getCode());
				resp.setMsg("活动还没开始");
				resp.setResult(fyjzhOrderResponse);
			} else if (now.compareTo(activityEnd) > 0) {
				resp.setResultCode(ResultCode.FAILED.getCode());
				resp.setMsg("活动已结束");
				resp.setResult(fyjzhOrderResponse);
			} else {
				Integer count = this.encourageHistoryService.findByOrderId(req.getOrderId());

				OrderInfo orderInfo = this.orderContent.findByOrderId(req.getOrderId());

				ProductInfo prod = prodService.findById(orderInfo.getProductId());

				if (count == 0) {
					if (orderInfo.getPayStatus() == ConstantOrderStatus.PAY_STATUS_TRUE) {
						// 检查是否是京华体验标的产品
						if (StringUtils.isNotEmpty(prod.getLabel01()) && prod.getLabel01().equals("京华专标")) {
							LocalDate today = LocalDate.now();
							String selectSql = "select id from t_product_info where label01 = '京华专标'";
							List<Map<String, Object>> results = this.jdbcTemplate.queryForList(selectSql);
							StringBuilder sb = new StringBuilder();
							sb.append("(");
							for (Map<String, Object> result: results) {
								sb.append(result.get("id") + ",");
							}
							sb = new StringBuilder(sb.substring(0, sb.length()-1));
							sb.append(")");

							Parameter oneDayMoney = parameterService.getByName(OneDayEncourageMoney);

							String sql = String.format(
									"select count(*) from t_order_info where productId in %s and userId = ? and orderCreatedOn >= ? and payStatus = 2 and realPayAmt >= %s",
									sb.toString(), oneDayMoney.getValue01().trim());

							Integer orderCount = this.jdbcTemplate.queryForObject(sql, new Object[]{
									orderInfo.getUserId(),
									Timestamp.valueOf(LocalDateTime.of(today, LocalTime.of(0, 0))).getTime()
							}, Integer.class);

							EncourageHistory encourageHistory = new EncourageHistory();
							encourageHistory.setOrderId(req.getOrderId());
							this.encourageHistoryService.add(encourageHistory);

							// 检查是不是专项标的第3、13、23、33...93笔（共计10笔）订单用户
							CouponResult threeEndCouponResult = this.orderContent.checkThreeEndUser(orderInfo, orderInfo.getProductId());
							fyjzhOrderResponse.setThreeEndEncourage(threeEndCouponResult.getFlag());
							fyjzhOrderResponse.setThreeEndEncourageEnough(threeEndCouponResult.getCount());

							// 个人单日首笔购买“京华专项标”≥3000元，送30元京东E卡
							CouponResult oneDayCouponResult = this.orderContent.checkOneDayEncourage(orderInfo, orderInfo.getProductId());
							fyjzhOrderResponse.setOneDayEncourage(oneDayCouponResult.getFlag());
							fyjzhOrderResponse.setOneDayEncourageEnough(oneDayCouponResult.getCount());

							// 个人连续三天（每三天一个循环）单日首笔购买“京华专项标”≥3000元
							CouponResult threeComboCouponResult = this.orderContent.checkThreeComboEncourage(orderInfo, orderInfo.getProductId());
							Integer flag = threeComboCouponResult.getCouponCount();

							Parameter threeComboEncourageTime = parameterService.getByName(ThreeComboEncourageTime);
							Integer threeTime = Integer.valueOf(threeComboEncourageTime.getValue01());

							fyjzhOrderResponse.setThreeComboEncourage(flag != 0 && flag % threeTime.intValue() == 0);
							fyjzhOrderResponse.setThreeComboEncourageEnough(threeComboCouponResult.getCount());

							fyjzhOrderResponse.setAlreadyFinishDay(flag == null ? 1 : flag);
							fyjzhOrderResponse.setCount(orderCount);

							if ((fyjzhOrderResponse.getThreeEndEncourage() && fyjzhOrderResponse.getThreeEndEncourageEnough()) ||
									(fyjzhOrderResponse.getOneDayEncourage() && fyjzhOrderResponse.getOneDayEncourageEnough()) ||
									(fyjzhOrderResponse.getThreeComboEncourage() && fyjzhOrderResponse.getThreeComboEncourageEnough()) ) {
								ExecutorService executor = Executors.newCachedThreadPool();
								Runnable task = new Runnable() {

									@Override
									public void run() {
										try {
											String tokenUrl = String.format("%s/getToken", AppOrderStrategyCtrl.this.msgServerHost);
											URI uri = new URI(tokenUrl);
											HttpGet httpGet = new HttpGet(uri);
											HttpClient httpClient = HttpClients.createDefault();
											HttpResponse response = httpClient.execute(httpGet);
											int statusCode = response.getStatusLine().getStatusCode();

											if(statusCode == HttpStatus.SC_OK){
												String body = EntityUtils.toString(response.getEntity());
												Gson gson = new Gson();
												ResponseBase responseBase = gson.fromJson(body, ResponseBase.class);
												String token = (String)responseBase.getResult();

												SysUser sysUser = AppOrderStrategyCtrl.this.sysUserService.findById(orderInfo.getUserId());

												String url = String.format("%s/sendMsg?content=%s&mobile=%s&token=%s",
														AppOrderStrategyCtrl.this.msgServerHost,
														"您已满足“投资满额送京东卡”活动条件，打开华财通“我的-我的优惠”即可查看专属礼品",
														sysUser.getName(),
														token);
												httpGet = new HttpGet(url);
												httpClient = HttpClients.createDefault();
												response = httpClient.execute(httpGet);
												statusCode = response.getStatusLine().getStatusCode();

												if (statusCode == HttpStatus.SC_OK) {
													body = EntityUtils.toString(response.getEntity());
													logger.info("msg server: " + body);
												}
											}
										} catch (Exception e) {
											logger.error("send message error: ", e);
										}
									}
								};
								executor.execute(task);
								executor.shutdown();

							}
						}

					}
				}

				resp.setResultCode(ResultCode.SUCC.getCode());
				resp.setResult(fyjzhOrderResponse);
			}

		}

		return resp;
	}


	@RequestMapping(value = "/encourage/can/{userId}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase canEncourage(@PathVariable Long userId) {
		ResponseBase responseBase = new ResponseBase();

		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss");

		Parameter jhActivityBegin = parameterService.getByName(JH_ACTIVITY_BEGIN);
		Parameter jhActivityEnd = parameterService.getByName(JH_ACTIVITY_END);

		LocalDateTime now = LocalDateTime.now();

		LocalDateTime activityBegin = LocalDateTime.parse(jhActivityBegin.getValue01(), dateTimeFormatter);
		LocalDateTime activityEnd = LocalDateTime.parse(jhActivityEnd.getValue01(), dateTimeFormatter);

		Map<String, Object> respResult = new HashMap<>();

		respResult.put("count", 0);
		respResult.put("begin", true);
		respResult.put("end", false);

		if (now.compareTo(activityBegin) < 0) {
			responseBase.setMsg("活动还没开始");
			respResult.put("begin", false);
		} else if (now.compareTo(activityEnd) > 0) {
			responseBase.setMsg("活动已结束");
			respResult.put("end", true);
		} else {
			LocalDate today = LocalDate.now();
			String selectSql = "select id from t_product_info where label01 = '京华专标'";
			List<Map<String, Object>> results = this.jdbcTemplate.queryForList(selectSql);
			StringBuilder sb = new StringBuilder();
			sb.append("(");
			for (Map<String, Object> result: results) {
				sb.append(result.get("id") + ",");
			}
			sb = new StringBuilder(sb.substring(0, sb.length()-1));
			sb.append(")");

			Parameter oneDayMoney = parameterService.getByName(OneDayEncourageMoney);
			String sql = String.format(
					"select count(*) from t_order_info where productId in %s and userId = ? and orderCreatedOn >= ? and payStatus = 2 and realPayAmt >= %s",
					sb.toString(), oneDayMoney.getValue01().trim());

			Integer count = this.jdbcTemplate.queryForInt(sql, new Object[] {
					userId,
					Timestamp.valueOf(LocalDateTime.of(today, LocalTime.of(0, 0))).getTime()
			});


			respResult.put("count", count);
		}
		responseBase.setResultCode(ResultCode.SUCC.getCode());
		responseBase.setResult(respResult);
		return responseBase;
	}

	@RequestMapping(value = "/orderContract/{orderId}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase getContract(@PathVariable Long orderId) {
		ResponseBase resp = new ResponseBase();

		OrderInfo orderInfo = orderService.findById(orderId);

		if(orderInfo == null){
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			resp.setMsg("该订单不存在");
			return resp;
		}

		List<Map<String, Object>> contracts = new ArrayList<>();

		List<OrderContract> contractsList = orderContractService.getOrderContractList(orderId);

		//旧订单直接从orderInfo 中取合同数据
		if(contractsList == null || contractsList.size() == 0 ){
			if(StringHelper.isNotEmpty(orderInfo.getContractUrlHTML())) {
				Map<String, Object> contract = new HashMap<>();
				contract.put("contractUrl", QN_PDF + orderInfo.getContractUrlHTML());
				contract.put("contractTitle", orderInfo.getContractTitle());
				contracts.add(contract);
			}
		}else{
		//新订单从orderContract中取数据
			for(OrderContract orderContract:contractsList) {
				if(StringHelper.isNotEmpty(orderContract.getContractHTMLUrl())){
					Map<String, Object> contract = new HashMap<>();
					contract.put("contractUrl", QN_PDF + orderContract.getContractHTMLUrl());
					contract.put("contractTitle", orderContract.getContractTitle());
					contracts.add(contract);
				}
			}
		}

		resp.setResult(contracts);

		if(contracts != null){
			resp.setSize(contracts.size());
		}else{
			resp.setSize(0);
		}
		resp.setResultCode(ResultCode.SUCC.getCode());
		return resp;
	}


	/**
	 * 创建订单接口,用富有金账户进行支付
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/getPopMsg", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseBase<Map<String, Object>> getPopMsg(@RequestBody OrderCommReq req) {

		logger.info("in getPopMsg orderId = {}", req.getOrderId());
		ResponseBase<Map<String, Object>> resp = new ResponseBase<Map<String, Object>>();

		Map<String, Object> map = new HashMap<>();

		if(req == null || req.getOrderId() == null){
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			logger.info("in getPopMsg orderId is null will return");
			return resp;
		}

		Long orderId = req.getOrderId();
		OrderInfo orderInfo = orderService.findById(orderId);
		if(orderInfo == null){
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			logger.info("in getPopMsg orderInfo is null  will return");
			return resp;
		}

		if (!RedisCilent.existsKey(orderId.toString())) {
			logger.info("key not in the redis , will return null");
			resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
			logger.info("in getPopMsg msg is null  will return");
			return resp;
		}

		//读取Redis中的参数
		String popMsg = RedisCilent.getString(orderId.toString());

		map.put("popMsg", popMsg);

		resp.setResult(map);

		resp.setMsg("消息获取成功");
		logger.info("消息获取成功");
		resp.setResultCode(ResultCode.SUCC.getCode());
		return resp;
	}

}
